package me.james.biuedittext;

import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorGroup;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.components.*;
import ohos.agp.utils.Color;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;

import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;

public class BiuEditText extends TextField {
    private static final int ANIMATION_UP = 0;
    private static final int ANIMATION_DOWN = 1;
    private ComponentContainer contentContainer;
    private int height;
    private String cacheStr = "";

    private Color biuTextColor;
    private float biuTextStartSize;
    private float biuTextScale;
    private int biuDuration;
    private int biuType;
    private int position;
    private Context context;
    private List<Text> list = new ArrayList<>();
    private float[] positions = new float[2];
    private SecureRandom secureRandom= new SecureRandom();
    private ComponentContainer.LayoutConfig layoutConfig;
    /**
     * 清空后手动设置焦点
     *
     * @param position
     */
    public void setPosition(int position) {
        this.position = position;
    }

    /**
     * 使用java代码实例化调用
     *
     * @param context
     */
    public BiuEditText(Context context) {
        super(context);
        this.context = context;
    }

    /**
     * 在xml布局中使用调用
     *
     * @param context
     * @param attrSet
     */
    public BiuEditText(Context context, AttrSet attrSet) {
        super(context, attrSet);
        this.context = context;
        init(context, attrSet);
    }

    /**
     * 在xml布局中使用并设置style调用
     *
     * @param context
     * @param attrSet
     * @param styleName
     */
    public BiuEditText(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
        this.context = context;
        init(context, attrSet);
    }

    public void setContentContainer(ComponentContainer contentContainer) {
        this.contentContainer = contentContainer;
    }

    private void init(Context context, AttrSet attrs) {
        if (attrs == null) {
            throw new IllegalArgumentException("Attributes should be provided to this view,");
        }
        biuTextColor = attrs.getAttr("biu_text_color").get().getColorValue();
        biuTextStartSize = attrs.getAttr("biu_text_start_size").get().getDimensionValue();
        biuTextScale = attrs.getAttr("biu_text_scale").get().getFloatValue();
        biuDuration = attrs.getAttr("biu_duration").get().getIntegerValue();
        String type = attrs.getAttr("biu_type").get().getStringValue();
        if (type.equals("flydown")) {
            biuType = ANIMATION_DOWN;
        } else if (type.equals("flyup")) {
            biuType = ANIMATION_UP;
        }
        layoutConfig = new ComponentContainer.LayoutConfig(
                ComponentContainer.LayoutConfig.MATCH_CONTENT,
                ComponentContainer.LayoutConfig.MATCH_CONTENT);
        height = DisplayManager.getInstance().getDefaultDisplay(context).get().getAttributes().height;
        setlistener();
    }

    private void setlistener() {
        addTextObserver(new TextObserver() {
            @Override
            public void onTextUpdated(String s, int i, int i1, int i2) {
                if (cacheStr.length() < s.length()) {
                    char last = s.charAt(position - 1);
                    update(last, false);
                } else if (cacheStr.length() > s.length()) {
                    char last = cacheStr.charAt(position);
                    update(last, true);
                }
                cacheStr = s;
            }
        });
        setCursorChangedListener(new CursorChangedListener() {
            @Override
            public void onCursorChange(TextField textField, int i, int i1) {
                position = i;
            }
        });
    }
    int u = 1;
    public void update(char last, boolean isOpposite) {
        Text textView;
        if (list.size() == 0) {
            textView = new Text(context);
            System.out.println("zyf-----------     new创建"+u++);
        } else {
            textView = list.get(0);
            list.remove(0);
        }
        textView.setTextColor(biuTextColor);
        textView.setTextSize((int) biuTextStartSize);
        textView.setText(String.valueOf(last));
        contentContainer.addComponent(textView, layoutConfig);
        playAnaimator(textView, isOpposite, new Animator.StateChangedListener() {
            @Override
            public void onStart(Animator animator) {
            }

            @Override
            public void onStop(Animator animator) {
                contentContainer.removeComponent(textView);
            }

            @Override
            public void onCancel(Animator animator) {
                contentContainer.removeComponent(textView);
            }

            @Override
            public void onEnd(Animator animator) {
                contentContainer.removeComponent(textView);
                list.add(textView);
            }

            @Override
            public void onPause(Animator animator) {
                contentContainer.removeComponent(textView);
            }

            @Override
            public void onResume(Animator animator) {
            }
        });
    }

    private void playAnaimator(Text textView, boolean isOpposite, Animator.StateChangedListener listenerAdapter) {
        switch (biuType) {
            case ANIMATION_UP:
                playFlyUp(textView, isOpposite, listenerAdapter);
                break;
            case ANIMATION_DOWN:
                playFlyDown(textView, isOpposite, listenerAdapter);
                break;
            default:
                break;
        }
    }

    private void playFlyDown(Text textView, boolean isOpposite, Animator.StateChangedListener listenerAdapter) {
        float startX = 0;
        float startY = 0;
        float endX = 0;
        float endY = 0;
        float[] coordinate = getCursorCoordinate();
        if (isOpposite) {
            endX = secureRandom.nextInt(contentContainer.getWidth());
            endY = 0;
            startX = coordinate[0];
            startY = coordinate[1];
        } else {
            startX = coordinate[0];
            startY = -100;
            endX = startX;
            endY = coordinate[1];
        }
        textView.setContentPositionY(startY);
        AnimatorProperty animX = textView.createAnimatorProperty().moveFromX(startX).moveToX(endX).moveFromY(startY).moveToY(endY);
        animX.setCurveType(Animator.CurveType.BOUNCE);
        animX.setDuration(biuDuration);
        animX.setStateChangedListener(listenerAdapter);
        animX.start();
    }

    private void playFlyUp(Text textView, boolean isOpposite, Animator.StateChangedListener listenerAdapter) {
        float startX = 0;
        float startY = 0;
        float endX = 0;
        float endY = 0;
        float[] coordinate = getCursorCoordinate();
        if (isOpposite) {
            endX = secureRandom.nextInt(contentContainer.getWidth());
            endY = height / 3 * 2;
            startX = coordinate[0];
            startY = coordinate[1];
        } else {
            startX = coordinate[0];
            startY = height / 3 * 2;
            endX = startX;
            endY = coordinate[1];
        }
        textView.setContentPositionY(startY);
        AnimatorProperty animX = textView.createAnimatorProperty().moveFromX(startX).moveToX(endX).moveFromY(startY).moveToY(endY).scaleXFrom(1f).scaleX(biuTextScale).scaleYFrom(1f).scaleY(biuTextScale);
        animX.setCurveType(Animator.CurveType.DECELERATE);
        animX.setDuration(biuDuration);
        animX.setStateChangedListener(listenerAdapter);
        animX.start();
    }

    /**
     * 获取光标的XY轴
     *
     * @return float[]
     */
    private float[] getCursorCoordinate() {
        float x = getContentPositionX();
        float y = getContentPositionY();
        positions[0] = x;
        positions[1] = y;
        return positions;
    }
}